package com.raven.craft.code.generator.common.constant;

import lombok.AllArgsConstructor;
import lombok.Getter;

/**
 * @author raven
 * @date 2019-06-06 11:57
 */
@Getter
@AllArgsConstructor
public enum SqlType implements BaseEnum<String> {

    TINYINT("tinyint"),
    SMALLINT("smallint"),
    MEDIUMINT("mediumint"),
    INT("int"),
    INTEGER("integer"),
    DOUBLE("double"),
    BIGINT("bigint"),
    DECIMAL("decimal"),

    DATE("date"),
    DATETIME("datetime"),
    TIMESTAMP("timestamp"),

    CHAR("char"),
    VARCHAR("varchar"),
    TINYBLOB("tinyblob"),
    TINYTEXT("tinytext"),
    BLOB("blob"),
    TEXT("text"),
    MEDIUMBLOB("mediumblob"),
    MEDIUMTEXT("mediumtext"),
    LONGBLOB("longblob"),
    LONGTEXT("longtext"),
    JSON("json"),
    ;

    private final String code;

    public JavaType toJavaType(Integer intergralLength, Integer fractionalLength) {
        switch (this) {
            case TINYINT:
            case SMALLINT:
                if (fractionalLength == null) {
                    if (intergralLength == null || intergralLength <= 1) {
                        return JavaType.BOOLEAN;
                    } else {
                        return JavaType.INTEGER;
                    }
                } else {
                    return JavaType.DOUBLE;
                }
            case MEDIUMINT:
            case INT:
            case INTEGER:
            case DOUBLE:
            case BIGINT:
            case DECIMAL:
                if (fractionalLength == null) {
                    if (intergralLength == null) {
                        return JavaType.DOUBLE;
                    } else if (intergralLength > 18) {
                        return JavaType.BIG_DECIMAL;
                    } else if (intergralLength > 9) {
                        return JavaType.LONG;
                    } else {
                        return JavaType.INTEGER;
                    }
                } else {
                    return JavaType.BIG_DECIMAL;
                }
            case DATE:
            case DATETIME:
            case TIMESTAMP:
                return JavaType.DATETIME;
            case CHAR:
            case VARCHAR:
            case TINYBLOB:
            case TINYTEXT:
            case BLOB:
            case TEXT:
            case MEDIUMBLOB:
            case MEDIUMTEXT:
            case LONGBLOB:
            case LONGTEXT:
            case JSON:
                return JavaType.STRING;
            default:
                throw new IllegalArgumentException("Unknown sqlType: " + this);
        }
    }

}
